# _*_ coding : utf-8 _*_
# @Time : 2024-05-29 14:25
# @Author : haowen
# @File : 10.人脸识别
# @Project : face identifying
import cv2

# 加载训练好的模型
recognizer = cv2.face.LBPHFaceRecognizer.create()
recognizer.read('trainer/trainer.yml')

# 加载分类器
face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')

# 加载待识别的图像
test_image = cv2.imread('test_image/t.JPG')
# test_image = cv2.imread('image/3.JPG')

# 转换为灰度图像
gray_test_image = cv2.cvtColor(test_image, cv2.COLOR_BGR2GRAY)

# 检测面部区域
faces = face_cascade.detectMultiScale(gray_test_image )

# 遍历检测到的每个面部
for (x, y, w, h) in faces:
    # 提取面部区域
    roi_gray = gray_test_image[y:y + h, x:x + w]

    # 预测ID和置信度
    id_, confidence = recognizer.predict(roi_gray)

    # 设定一个阈值，低于该阈值则认为是未知面部
    threshold = 70

    # 判断是否为未知面部
    if confidence < threshold:
        id_str = "Unknown"
    else:
        id_str = f"ID: {id_}"

        # 打印结果
    print(f"Predicted: {id_str}, Confidence: {confidence}")

    # 在图像上绘制矩形和文本
    cv2.rectangle(test_image, (x, y), (x + w, y + h), (0, 255, 0), 2)
    font = cv2.FONT_HERSHEY_SIMPLEX
    cv2.putText(test_image, id_str, (x, y - 10), font, 1, (255, 255, 255), 2, cv2.LINE_AA)

# 显示图像
cv2.imshow('Test Image', test_image)
cv2.waitKey(0)
cv2.destroyAllWindows()